import json
from flask import Flask, request, render_template, session, redirect, jsonify

import AudioLocation
import judgement
import transform
from sqldb import *

now_user = []

app = Flask("__name__")
app.config['SECRET_KEY'] = '123456'


# 注册
@app.route("/signin")
def signin_index():
    return app.send_static_file("signin.html")


@app.route("/CheckUserID", methods=("POST",))
def checkPrime():
    netname = request.form['username'].strip()
    print("当前用户：" + netname)
    check_rst = search_user(netname)
    if len(check_rst) == 0:
        return "1"
    else:
        return "0"


@app.route("/CheckUser", methods=("POST",))
def checkUser():
    netname = request.form['username'].strip()
    pwd = request.form['pwd1'].strip()
    check_user = login(netname, pwd)
    if (check_user == '1'):
        return "1"
    else:
        return "0"


@app.route("/Register", methods=("POST",))
def webRegister():
    netname = request.form['username'].strip()
    pwd1 = request.form['pwd1']
    create_user(str(netname), str(pwd1))
    return app.send_static_file("login.html")


# 登录
@app.route("/login")
def login_index():
    return app.send_static_file("login.html")


@app.route("/Login", methods=("POST",))
def webLogin():
    netname = request.form['username'].strip()
    pwd1 = request.form['pwd1']
    login_rst = login_user(netname, pwd1)
    if login_rst[0]:
        session['username'] = login_rst[1]
        if session['username'] not in now_user:
            now_user.append(session['username'])
        else:
            session.pop('username', None)
            return redirect("/chessPlay")
    return redirect("/login")


@app.route("/judge", methods=("POST",))
def judge():
    result = json.loads(request.form.get('data'))
    i = result.get('i')
    j = result.get('j')

    # print(i)
    # print(j)
    flag = judgement.judge(i, j)

    if flag == 1:
        return jsonify({"success": 200, "status": "白棋获胜", "flag": "true"})
    if flag == 2:
        return jsonify({"success": 200, "status": "黑棋获胜", "flag": "true"})

    return " "
    pass


@app.route('/chessPlay')
def chessPlay():
    return render_template("chess.html")


@app.route('/audio', methods=['POST', 'GET'])
def audio():
    location = AudioLocation.getLocation()
    position = transform.match(location)
    line = position[0]
    row = position[1]
    print(line)
    print(row)
    try:
        x = line
        y = row
    except ValueError or AttributeError or TypeError:
        return {
            "x": 0,
            "y": 0,
            "msg": False
        }
    if 0 <= x <= 14 and 1 <= y <= 15:
        return {
            "x": x,
            "y": y - 1,  # 从0开始
            "msg": True
        }
    else:
        return {
            "x": 0,
            "y": 0,
            "msg": False
        }

@app.route('/')
def root_web():
    return redirect('/login')


if __name__ == '__main__':
    app.jinja_env.auto_reload = True
    app.run(debug=True)
